<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>聊天</title>
  <link rel="stylesheet" type="text/css" href="css/main.css" />
  <link rel="stylesheet" type="text/css" href="css/index.css" />
</head>

<body class="flex">
  <nav class="navs flex-column jcsb">
    <div class="nav-ctrl">
      <button class="flex jcc aic" onclick="app.switchContactListType(false, event)">好友</button>
      <button class="flex jcc aic" onclick="app.switchContactListType(true, event)">群聊</button>
    </div>
    <button class="flex jcc aic" id="logout-btn" onclick="app.logout()">退出</button>
  </nav>
  <div class="friend flex-column">
    <div id="currnt_type_title" class="title flex jcc aic">好友列表</div>
    <div id="contact_list">
      <div class="contact-item cp">
        <img class="avatar"
          src="https://dss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1906469856,4113625838&fm=26&gp=0.jpg">
        <div class="txt-add">test</div>
      </div>
    </div>
  </div>
  <div class="chat f1 flex-column jcsb">
    <h3 class="flex jcc aic">当前聊天对象名</h3>
    <ul id="chat_list" class="f1"></ul>
    <textarea id="chat_textarea" cols="30" rows="10" placeholder="请输入聊天内容" autofocus
      onkeydown="app.keydown(event)"></textarea>
    <button class="send-btn square" onclick="app.sendMessage()">发送</button>
  </div>

  <script src="//cdn.ronghub.com/RongIMLib-2.5.5.js"></script>
  <script src="js/http.js"></script>
  <script src="js/main.js"></script>
  <script>
    const app = new (class extends Base {
      constructor() {
        super()
        // 当前信息
        this.userinfo = {}

        this.logout_btn = this.query('#logout-btn')
        this.chat_list = this.query('#chat_list')
        this.chat_textarea = this.query('#chat_textarea')
        this.init()
      }

      // initial

      async init() {
        // 检查有没有登录
        this.initRongYun()
      }

      async initRongYun() {
        RongIMLib.RongIMClient.init('0vnjpoad03jyz')
        // 连接状态监听
        RongIMClient.setConnectionStatusListener({
          onChanged: (status) => {
            // status 标识当前连接状态
            switch(status) {
              case RongIMLib.ConnectionStatus.CONNECTED:
                console.log('链接成功')
                break
              case RongIMLib.ConnectionStatus.CONNECTING:
                console.log('正在链接')
                break
              case RongIMLib.ConnectionStatus.DISCONNECTED:
                console.log('断开连接')
                break
              case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
                console.log('其他设备登录, 本端被踢')
                break
              case RongIMLib.ConnectionStatus.DOMAIN_INCORRECT:
                console.log('域名不正确, 请至开发者后台查看安全域名配置')
                break
              case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
                console.log('网络不可用, 此时可调用 reconnect 进行重连')
                break
              default:
                console.log('链接状态为', status)
                break
            }
          }
        })
        // 收到消息监听
        RongIMClient.setOnReceiveMessageListener({
          // 接收到的消息
          onReceived: res => {
            let messageContent = res.content
            // 判断消息类型
            switch(res.messageType) {
              case RongIMClient.MessageType.TextMessage: // 文字消息
                console.log('文字内容', messageContent.content)
                // res.senderUserId
                console.log(res)
                this.reciveMessage(res)
                break
              case RongIMClient.MessageType.ImageMessage: // 图片消息
                console.log('图片缩略图 base64', messageContent.content)
                console.log('原图 url', messageContent.imageUri)
                break
              case RongIMClient.MessageType.HQVoiceMessage: // 音频消息
                console.log('音频 type ', messageContent.type) // 编解码类型，默认为 aac 音频
                console.log('音频 url', messageContent.remoteUrl) // 播放：<audio src={remoteUrl} />
                console.log('音频 时长', messageContent.duration)
                break
              case RongIMClient.MessageType.RichContentMessage: // 富文本(图文)消息
                console.log('文本内容', messageContent.content)
                console.log('图片 base64', messageContent.imageUri)
                console.log('原图 url', messageContent.url)
                break
              case RongIMClient.MessageType.UnknownMessage: // 未知消息
                console.log('未知消息, 请检查消息自定义格式是否正确', message)
                break
              default:
                console.log('收到消息', res)
                this.reciveMessage(res)
                break
            }
          }
        })
        // 获取连接 token
        let ret = await http.post('/api/token', {
          userId: '1',
          name: 'root',
          portraitUri: 'https://dss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1906469856,4113625838&fm=26&gp=0.jpg',
        })

        if(ret) {
          console.log(ret)
          let token = ret.token

          // 融云连接
          RongIMClient.connect(token, {
            onSuccess: (userId) => {
              console.log('连接成功, 用户 id 为', userId)
            },
            onTokenIncorrect: () => {
              console.log('连接失败, 失败原因: token 无效')
            },
            onError: (errorCode) => {
              let info = ''
              switch(errorCode) {
                case RongIMLib.ErrorCode.TIMEOUT:
                  info = '链接超时'
                  break
                case RongIMLib.ConnectionState.UNACCEPTABLE_PAROTOCOL_VERSION:
                  info = '不可接受的协议版本'
                  break
                case RongIMLib.ConnectionState.IDENTIFIER_REJECTED:
                  info = 'appkey 不正确'
                  break
                case RongIMLib.ConnectionState.SERVER_UNAVAILABLE:
                  info = '服务器不可用'
                  break
                default:
                  info = errorCode
                  break
              }
              console.log('连接失败, 失败原因: ', info)
            }
          })
        }
      }

      // inner func

      disconnectRongYun() {
        RongIMClient.getInstance().disconnect()
      }

      async sendMessage() {
        let message = this.chat_textarea.value
        console.log(message)
        // 创建聊天气泡
        let msg = new RongIMLib.TextMessage({ content: message, extra: '附加信息' })

        RongIMClient.getInstance().sendMessage(RongIMLib.ConversationType.PRIVATE, '2', msg, {
          onSuccess: res => {
            console.log(message)
            // message 为发送的消息对象并且包含服务器返回的消息唯一 id 和发送消息时间戳
            console.log('发送文本消息成功: ', message)
            this.chat_list.innerHTML += `<li class="flex jcfe aic">${message} :我<img class="avatar" src="https://dss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1906469856,4113625838&fm=26&gp=0.jpg" alt="avatar"></li>`
            // 队列处理清空
            setTimeout(() => {
              this.chat_textarea.value = ''
            }, 0)
          },
          onError: errorCode => {
            console.log('发送文本消息失败', errorCode)
          }
        })
      }

      reciveMessage({ content }) {
        this.chat_list.innerHTML += `<li class="flex aic"><img  class="avatar"src="https://dss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1906469856,4113625838&fm=26&gp=0.jpg" alt="avatar">test: ${content.content}</li>`
      }

      // event
      keydown(e) {
        let key_code = e.keyCode
        // 13 为回车
        if(key_code === 13) {
          // 阻止换行
          e.preventDefault()
          let value = e.target.value
          if(value) {
            this.sendMessage()
          }
        }
      }

      switchContactListType() {
        alert('已关闭')
      }

      logout() {
        // 退出融云用户
        RongIMClient.getInstance().logout()
        location.replace('./login.html')
      }
    })()
  </script>
</body>

</html>